package com.rightsidetech.http.aspect;

import cn.hutool.core.date.DateUtil;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.rightsidetech.commom.enums.ModifyName;
import com.rightsidetech.commom.service.IService;
import com.rightsidetech.commom.utils.RedisUtils;
import com.rightsidetech.commom.utils.SpringUtil;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.mall.dto.response.MallAgentCommodityResp;
import com.rightsidetech.system.dtos.dto.LogInfoDTO;
import com.rightsidetech.http.log.parser.ContentParser;
import com.rightsidetech.system.entity.SysAgentLoginInfo;
import com.rightsidetech.system.entity.SysUserLoginInfo;
import com.rightsidetech.system.service.SysAgentInfoService;
import com.rightsidetech.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: yhr
 * @Date: 2021-11-11 10:05
 */
@Aspect
@Component
@Slf4j
public class ModifyLogAspect extends BaseController {
    @Autowired
    private RedisUtils redisUtils;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;

    @Around("@annotation(modifyLog)")
    public Object doAround(ProceedingJoinPoint point, ModifyLog modifyLog) throws Throwable {
        return this.logRecord(point, modifyLog);
    }

    public Object logRecord(ProceedingJoinPoint point, ModifyLog modifyLog) throws Throwable {
        Object object = null;
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        LogInfoDTO dto = new LogInfoDTO();
        boolean isAdmin = false;
        String token = null;
        boolean isList = false;
        ContentParser contentParser = null;
        if (!StringUtils.isEmpty(request.getHeader("token_admin"))) {
            token = request.getHeader("token_admin");
            isAdmin = true;
        } else if (!StringUtils.isEmpty(request.getHeader("token_agentAdmin"))) {
            token = request.getHeader("token_agentAdmin");
        } else {
            token = request.getHeader("token_agentApp");
        }
        Long loginInfoId = null;
        if (!StringUtil.isNullorEmpty(token)) {
            //用户id
            loginInfoId = sysUserService.sysUsercheckToken(token);
            if (StringUtils.isEmpty(loginInfoId)) {
                loginInfoId = sysAgentInfoService.sysUsercheckToken(token);
            }
        }

        try {
            if (!ModifyName.SAVE.equals(modifyLog.modifyType())) {
                contentParser = (ContentParser) SpringUtil.getBean(modifyLog.parseClass());
                dto.setOldParam(contentParser.getResult(point, modifyLog));
                Class entityClass = modifyLog.entityClass();
                if (!IService.class.equals(entityClass)) {
                    dto.setOldParamList(Collections.singletonList(dto.getOldParam()));
                    isList = true;
                }
            }
        } catch (Exception e) {
            log.error("日志拦截处理前出错", e);
        }
        object = point.proceed();
        Map<String, Object> result = (Map<String, Object>) objectToMap(object);
        if (result.get("codeId") == null || !"1".equals(result.get("codeId").toString())) {
            return object;
        }
        if (!StringUtil.isNullorEmpty(loginInfoId)) {
            String loginName = null;
            if (isAdmin) {
                SysUserLoginInfo sysUserLoginInfo = sysUserService.selectUserById(loginInfoId);
                loginName = ObjectUtils.isEmpty(sysUserLoginInfo) ? null : sysUserLoginInfo.getLoginName();
            } else  {
                SysAgentLoginInfo sysAgentLoginInfo = sysAgentInfoService.selectInfoById(loginInfoId);
                loginName = ObjectUtils.isEmpty(sysAgentLoginInfo) ? null : sysAgentLoginInfo.getLoginName();
                dto.setAgentId(sysAgentLoginInfo.getAgentInfoId());
            }
            Object[] args = point.getArgs();
            if (args != null && args.length > 0) {
                dto.setParam(args[0]);
            }
            if (ModifyName.SAVE.equals(modifyLog.modifyType()) || ModifyName.UPDATE_SAVE.equals(modifyLog.modifyType())) {
                dto.setNewParam(dto.getParam());
            } else {
                dto.setNewParam(contentParser.getResult(point, modifyLog));
                dto.setNewParamList(Collections.singletonList(contentParser.getResult(point, modifyLog)));
            }
            dto.setAccountId(loginInfoId);
            dto.setLoginName(loginName);
            dto.setUri(request.getRequestURI());
            dto.setCreatedAt(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            if (isList) {
                List<MallAgentCommodityResp> oldList = castList(dto.getOldParamList().get(0), modifyLog.entityClass());
                List<MallAgentCommodityResp> newList = castList(dto.getNewParamList().get(0), modifyLog.entityClass());
                for (int i = 0; i < oldList.size(); i++) {
                    dto.setOldParam(oldList.get(i));
                    dto.setNewParam(newList.get(i));
                    String s = JSON.toJSONString(dto);
                    redisUtils.publishString("OPERATOR_LOG", s);
                }
            } else {
                String s = JSON.toJSONString(dto);
                redisUtils.publishString("OPERATOR_LOG", s);
            }

        }
        return object;
    }

    private Map<?, ?> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        Map<?, ?> mappedObject = mapper.convertValue(obj, Map.class);
        return mappedObject;
    }

    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }


}
